//index.js
//获取应用实例
const util = require("../../utils/util.js");
const app = getApp();
const adminOpenid = "ox7IZ4yeo5XWBLtMqgUUKkVMs_ks";

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    color: app.ext.color,
    logged: false,
    head_img: "../../images/logo.png",
    nick_name: "可视化小程序"
  },
  onLoad: function () {
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        if (res.result.openid == adminOpenid) {
          wx.setStorageSync("isAdmin", true);
        } else {
          wx.setStorageSync("isAdmin", false);
        }
        wx.setStorageSync("openid", res.result.openid);
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  onBack:function(e){
    wx.navigateBack();
  },
  onGetUserInfo: function (e) {
    if (!this.logged && e.detail.userInfo) {
      wx.cloud.callFunction({
        // 云函数名称
        name: 'user-add',
        // 传给云函数的参数
        data: {
          nick_name: e.detail.userInfo.nickName,
          gender: e.detail.userInfo.gender,
          language: e.detail.userInfo.language,
          city: e.detail.userInfo.city,
          province: e.detail.userInfo.province,
          avatar_url: e.detail.userInfo.avatarUrl,
          country: e.detail.userInfo.country,
          createtime: util.formatTime(new Date()),
          openid: wx.getStorageSync('openid'),
          dz: -1
        },
        complete: res => {
          console.log(e.detail)
          wx.setStorageSync('userInfo', e.detail.userInfo);
          wx.navigateBack();
          console.log('callFunction test result: ', res)
        }
      })
    } else {
      wx.redirectTo({
        url: '/pages/login/index',
        fail: res => {
          console.log(res);
        }
      })
    }
  }
})